/**
 * Copyright (C) 2016 Eshore Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eshore.thrpc.server.thrift;

import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.ServerContext;
import org.apache.thrift.server.TServerEventHandler;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eshore.thrpc.common.ServerNode;

/**
 * Thrift事件处理器
 * <p>
 * 
 * @author : zhouzhixiang
 * @date : 2015-6-8
 */
public class ThriftEventHandler implements TServerEventHandler {
	/** LOGGER */
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    /** {@link ServerNode} */
	private final ServerNode serverNode;

    /**
     * @param serverNode
     *            {@link ServerNode}
     */
    public ThriftEventHandler(ServerNode serverNode) {
        this.serverNode = serverNode;
    }

    @Override
    public ServerContext createContext(TProtocol in, TProtocol out) {
        LOGGER.info("client connecting to the server:{}",serverNode.getName());
        return null;
    }

    @Override
    public void deleteContext(ServerContext arg0, TProtocol in, TProtocol out) {
    	if(serverNode.isNonBlock()){
    		LOGGER.info("disconnecting to the server:{}",serverNode.getName());
    	}else{
    		TSocket socket = (TSocket)in.getTransport();  
            LOGGER.info("{} disconnecting to the server:{}",socket.getSocket().getRemoteSocketAddress(),serverNode.getName());
    	}
    	in.getTransport().close();
    	out.getTransport().close();
    }

    @Override
    public void preServe() {
        
    }

    @Override
    public void processContext(ServerContext arg0, TTransport in, TTransport out) {
        // TODO:进行ip白名单相关的校验
    }

}
